package com.seculab.admin.web;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.seculab.admin.domain.User;
import com.seculab.admin.service.LoginService;
import com.seculab.admin.web.validator.LoginValidator;

@Controller
@RequestMapping("/login")
public class LoginController {
	
	private LoginService loginService;
	private LoginValidator loginValidator;
	
	@Autowired
	public void init(LoginValidator loginValidator, LoginService loginService) {
		this.loginValidator = loginValidator;
		this.loginService = loginService;
	}

	@RequestMapping(method=RequestMethod.GET)
	public String login(@ModelAttribute User user) {
		System.out.println("login controller started");
		return "loginForm";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String login(Model model, HttpSession session, @ModelAttribute User user, BindingResult result) throws Exception {
		loginValidator.validate(user, result);
		
		if (result.hasErrors()) {
			return "loginForm";
		} else {
			Map<String, Object> resultMap = (Map<String, Object>)loginService.login(user);
			
			if(resultMap == null) {
				model.addAttribute("errors", "회원 정보가 존재하지 않습니다.");
				
				return "loginForm";
			} else {
				session.setAttribute("loginUser", resultMap);
			}
			
			return "redirect:company/userList";
		}		
	}
	
}
